import { defineStore } from 'pinia';
import { store } from '@/store';
import { type LoginParam, type UserResult, getLogin } from '@/api/user';
import { setToken } from '@/utils/auth';

export const useUserStore = defineStore({
  id: 'znl-user',
  state: () => ({}),
  actions: {
    async login(data: LoginParam) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then(res => {
            if (res.access_token) {
              setToken({ ...res, ...data });
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
  },
});

export function useUserStoreHook() {
  return useUserStore(store);
}
